//
//  Data+Extension.swift
//  8btc
//
//  Created by Steven Xie on 2018/11/15.
//  Copyright © 2018 Hangzhou Shichuo Information Technology Co, Ltd. All rights reserved.
//

public extension Date {
    func fix8BTCTimeToCNTime() -> Date {
        let dateFormat = DateFormatter()
        dateFormat.dateFormat = "yyyyMMdd-HH:mm:ss Zz"
        dateFormat.timeZone = TimeZone(identifier: "GMT+0000") // NSTimeZone.init(name: "GMT+0000") as TimeZone!
        let errorTimeString = dateFormat.string(from: self)
        let rightTimeString = errorTimeString.replacingOccurrences(of: "+0000GMT", with: "+0800GMT+8")
        return dateFormat.date(from: rightTimeString)!
    }

    func humanReadable(timeZone: TimeZoneType = .local, _ symbol: String = ".") -> String {
        if compare(.isToday) {
            return toStringWithRelativeTime() + " "
        } else if compare(.isYesterday) {
            return NSLocalizedString("yesterday", comment: "Date format") + " " + toString(format: .custom("HH:mm"), timeZone: timeZone) // toString(dateStyle: .none, timeStyle: .short)
        } else if compare(.isThisWeek) {
            return toStringWithRelativeTime()
        } else
        if compare(.isThisYear) {
            return toString(format: .custom("MM\(symbol)dd HH:mm"), timeZone: timeZone)
        } else {
            return toString(format: .custom("yyyy\(symbol)M\(symbol)d HH:mm"), timeZone: timeZone)
        }
    }

    func detailTimeString(timeZone: TimeZoneType = .local, _ symbol: String = ".") -> String {
        if compare(.isThisYear) {
            return toString(format: .custom("MM\(symbol)dd HH:mm"), timeZone: timeZone)
        } else {
            return toString(format: .custom("yyyy\(symbol)M\(symbol)d HH:mm"), timeZone: timeZone)
        }
    }

    func normalDay(_ timeZone: TimeZoneType = .local) -> String {
        return toString(format: .custom("yyyyMMdd"), timeZone: timeZone)
    }

    func getTimeStamp() -> String {
        let timeInterval: TimeInterval = timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        return String(timeStamp)
    }
}

public extension Data {
    var transform_json: [String: Any]? {
        do {
            return try JSONSerialization.jsonObject(with: self, options: .allowFragments) as? [String: Any]
        } catch {
            return nil
        }
    }
}
